<?php


if (!defined('FAMOUS_ROOT')) {
    exit('Access Denied');
}

/**
 * 执行内存存储命令
 *
 * @param string $cmd
 * @param string $key
 * @param mixed $value
 * @param integer $ttl
 * @return boolean|null
 */
function memory($cmd, $key = '', $value = '', $ttl = 0)
{
    global $_G;

    $weibo = &famous_core::instance();

    if ($cmd == 'check') {
        return $weibo->mem->enable ? $weibo->mem->type : '';
    } elseif ($weibo->mem->enable && in_array($cmd, array('set','get','rm'))) {
        switch ($cmd) {
            case 'set':
                return $weibo->mem->set($key, $value, $ttl);
                break;
            case 'get':
                return $weibo->mem->get($key);
                break;
            case 'rm':
                return $weibo->mem->rm($key);
                break;
        }
    }

    return null;
}

/**
 * 执行数据库存储命令
 *
 * @param string $cmd
 * @param string $key
 * @param mixed $value
 * @param integer $ttl
 * @return boolean|null
 */
function dbcache($cmd, $key, $value = '', $ttl = 0)
{
    global $_G;

    $key = daddslashes($key);

    if ($cmd == 'set') { // 设置缓存

        $serialize = 0;
        $value = daddslashes($value);
        if (is_array($value) || is_object($value)) {
            $value = serialize($value);
            $serialize = 1;
        }
        // 设置缓存有效期
        $expiry = ($ttl > 0) ? $_G['timestamp'] + $ttl : 0;
        $data = array(
            'cache_key' => $key,
            'cache_value' => $value,
            'cache_serialize' => $serialize,
            'cache_expiry_time' => $expiry);

        DB::insert('common_cache', $data, false, true);

    } elseif ($cmd == 'get') { // 取出缓存

        $data = DB::fetch_first("SELECT * FROM " . DB::table('common_cache') . " WHERE `cache_key`='{$key}'");
        if (empty($data)) {
            return null;
        }
        // 清除过期缓存
        if ($data['cache_expiry_time'] && $data['cache_expiry_time'] <= $_G['timestamp']) {
            dbcache('rm', $key);
            return null;
        }

        return ($data['cache_serialize']) ? unserialized($data['cache_value']) : $data['cache_value'];

    } elseif ($cmd == 'rm') { // 删除缓存

        DB::delete('common_cache', array('cache_key' => $key));

    }

    return null;
}


/**
 * 生成文件
 * @param path 根据path后缀判断生成包含数组的文件还是静态内容文件
 */
function makedata($message, $path)
{
    $data = strrchr($path, ".") == ".php" ? "<?php\n $message ?>" : $message;
    dmkdir($path);
    if (!$fp = @fopen($path, "wb")) {
        exit("无法生成文件 $path");
    }
    flock($fp, LOCK_EX);
    if (!@fwrite($fp, $data)) {
        flock($fp, LOCK_UN);
        exit("无法写入文件 $path");
    } else {
        flock($fp, LOCK_UN);
        return true;
    }
}

/**
 * 将数组转换成字符串，与makedata函数配合使用
 */
function arrayeval($array, $level = 0)
{

    if (!is_array($array)) {
        return "'" . $array . "'";
    }
    if (is_array($array) && function_exists('var_export')) {
        return var_export($array, true);
    }

    $space = '';
    for ($i = 0; $i <= $level; $i++) {
        $space .= "\t";
    }
    $evaluate = "Array\n$space(\n";
    $comma = $space;
    if (is_array($array)) {
        foreach ($array as $key => $val) {
            $key = is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;
            $val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\'' . addcslashes($val, '\'\\') . '\'' : $val;
            if (is_array($val)) {
                $evaluate .= "$comma$key => " . arrayeval($val, $level + 1);
            } else {
                $evaluate .= "$comma$key => $val";
            }
            $comma = ",\n$space";
        }
    }
    $evaluate .= "\n$space)";
    return $evaluate;
}






/**
 * 取出数据分析数据库链接句柄
 */
function getAnalyticsDb($num = 2, $istask = 0)
{
    $db = new db_mysql();
    $db->set_config(getglobal('config/db'));
    $r = $db->connect($num, $istask);
    if ($istask) {
        if (!$r) {
            return false;
        } else {
            return $db;
        }
    }
    return $db;
}

/**
 * 清除所有cookie记录
 *
 * @return void
 */
function clearcookies()
{
    global $_G;
    unset($_G['cookie']['last_view']);
    foreach ($_G['cookie'] as $k => $v) {
        dsetcookie($k);
    }

    $_G['uid'] = $_G['adminid'] = 0;
    $_G['username'] = $_G['member']['password'] = '';
}

/**
 * 返回分页数据
 *
 * @param integer $total 总数
 * @param integer $perpage 分页数
 * @param integer $curpage 当前页数
 * @param integer $maxpages 最大页数
 * @param integer $page 列出的页数
 * @return array
 */
function getpagedata($total, $perpage, $curpage, $maxpages = 0, $page = 5)
{
    $data = array();

    if ($total > $perpage) {

        $offset = floor($page * 0.5);
        $data['curpage'] = $curpage;
        $data['realpages'] = @ceil($total / $perpage);
        $pages = $maxpages && $maxpages < $data['realpages'] ? $maxpages : $data['realpages'];

        if ($page > $pages) {
            $from = 1;
            $to = $pages;
        } else {
            $from = $curpage - $offset;
            $to = $from + $page - 1;
            if ($from < 1) {
                $to = $curpage + 1 - $from;
                $from = 1;
                if ($to - $from < $page) {
                    $to = $page;
                }
            } elseif ($to > $pages) {
                $from = $pages - $page + 1;
                $to = $pages;
            }
        }

        $data['firstpage'] = 1;
        $data['prevpage'] = ($curpage > 1 ? $curpage - 1 : '');
        $data['nextpage'] = ($curpage < $pages ? $curpage + 1 : '');
        $data['lastpage'] = $pages;
        $data['from'] = $from;
        $data['to'] = $to;

        for ($i = $from; $i <= $to; $i++) {
            $data['multi'][] = $i;
        }
    }

    return $data;
}


/**
 * 引用系统模块文件路径
 *
 * <p>引入文件 source/module/weibo/weibo_index.php 示例:</p>
 * <code>
 * require libfile('weibo/index', 'module');
 * </code>
 *
 * @param string $libname
 * @param string $folder
 * @return string
 */
function libfile($libname, $folder = '')
{
    $libpath = FAMOUS_ROOT . '/source/' . $folder;
    if (strstr($libname, '/')) {
        list($pre, $name) = explode('/', $libname);        
        return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
    } else { 
        return realpath("{$libpath}/{$libname}.php");
    }
}

/**
 * 加载系统配置文件
 *
 * @param string $name
 * @return void
 */
function loadconfig($name)
{
    global $_G;

    $config_path = FAMOUS_ROOT . './config/'.ENVIRONMENT.'/config_' . $name . '.php';
    if(file_exists($config_path)){
        @include $config_path;
    } else {
        @include FAMOUS_ROOT . './config/config_' . $name . '.php';
    }

    if (!empty($_config)) {
        $_G['config'] = array_merge($_G['config'], $_config);
    }
}

/**
 * 加载UCenter配置文件和库文件
 */
function loaducenter()
{
    //weibo.pp.cc
    $weibo = WEIBO_SINA ? '_weibo' : '';
    $config_path = FAMOUS_ROOT . './config/'.ENVIRONMENT.'/config_ucenter' . $weibo . '.php';
    if(file_exists($config_path)){
        @include $config_path;
    } else {
        @include FAMOUS_ROOT . './config/config_ucenter' . $weibo . '.php';
    }

    require_once FAMOUS_ROOT . './uc_client/client.php';
}

/**
 * 模板
 *
 * @param string $file
 * @param integer $templateid
 * @param string $tpldir
 * @param integer $gettplfile
 * @param string $primaltpl
 * @return string
 */
function template($file, $templateid = 0, $tpldir = '', $gettplfile = 0, $primaltpl = '')
{
    global $_G;
    static $_init_style = false;

    if ($_init_style === false) {
        $weibo = &famous_core::instance();
        $weibo->_init_style();
        $_init_style = true;
    }

    if (strexists($file, ':')) {
        $file .= ':';
        $clonefile = '';
        list($templateid, $file, $clonefile) = explode(':', $file);
        $oldfile = $file;
        $file = empty($clonefile) ? $file : $file . '_' . $clonefile;
        if ($templateid == 'diy') {
            $_G['style']['prefile'] = '';
            $diypath = FAMOUS_ROOT . './data/diy/';
            $preend = '_diy_preview';
            $previewname = $diypath . $file . $preend . '.htm';
            $_G['gp_preview'] = !empty($_G['gp_preview']) ? $_G['gp_preview'] : '';
            $curtplname = $oldfile;
            if (file_exists($diypath . $file . '.htm')) {
                $tpldir = 'data/diy';
                !$gettplfile && $_G['style']['tplsavemod'] = 1;

                $curtplname = $file;
                $flag = file_exists($previewname);
                if ($_G['gp_preview'] == 'yes') {
                    $file .= $flag ? $preend : '';
                } else {
                    $_G['style']['prefile'] = $flag ? 1 : '';
                }

            } elseif (file_exists($diypath . ($primaltpl ? $primaltpl : $oldfile) . '.htm')) {
                $file = $primaltpl ? $primaltpl : $oldfile;
                $tpldir = 'data/diy';
                !$gettplfile && $_G['style']['tplsavemod'] = 0;

                $curtplname = $file;
                $flag = file_exists($previewname);
                if ($_G['gp_preview'] == 'yes') {
                    $file .= $flag ? $preend : '';
                } else {
                    $_G['style']['prefile'] = $flag ? 1 : '';
                }

            } else {
                $file = $primaltpl ? $primaltpl : $oldfile;
            }

            $tplrefresh = $_G['config']['output']['tplrefresh'];

            if ($tplrefresh == 1) { // 自动刷新模板
                $tplmtime = @filemtime($diypath . $file . '.htm');
                if ($tpldir == 'data/diy' && ($tplrefresh == 1 || ($tplrefresh > 1 && !($_G['timestamp'] % $tplrefresh))) && $tplmtime && $tplmtime < @filemtime(FAMOUS_ROOT . TPLDIR . '/' . ($primaltpl ? $primaltpl : $oldfile) . '.htm')) {
                    if (!updatediytemplate($file)) {
                        @unlink($diypath . $file . '.htm');
                        $tpldir = '';
                    }
                }
            }

            if (!$gettplfile && empty($_G['style']['tplfile'])) {
                $_G['style']['tplfile'] = empty($clonefile) ? $curtplname : $oldfile . ':' . $clonefile;
            }

            $_G['style']['prefile'] = !empty($_G['gp_preview']) && $_G['gp_preview'] == 'yes' ? '' : $_G['style']['prefile'];

        } else {
            $tpldir = './source/plugin/' . $templateid . '/template';
        }
    }

    $file .= !empty($_G['inajax']) && ($file == 'common/header' || $file == 'common/footer') ? '_ajax' : '';
    $tpldir = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : '');
    $templateid = $templateid ? $templateid : (defined('TEMPLATEID') ? TEMPLATEID : '');
    $tplfile = ($tpldir ? $tpldir . '/' : './template/') . $file . '.htm';
    $filebak = $file;
    $file == 'common/header' && defined('CURMODULE') && CURMODULE && $file = 'common/header_' . $_G['basescript'] . '_' . CURMODULE;
    $cachefile = './data/template/' . (defined('STYLEID') ? STYLEID . '_' : '_') . $templateid . '_' . str_replace('/', '_', $file) . '.tpl.php';
    // exit($tplfile);
    if ($templateid != 1 && !file_exists(FAMOUS_ROOT . $tplfile)) {
        $tplfile = './template/default/' . $filebak . '.htm';
    }

    if ($gettplfile) {
        return $tplfile;
    }


    checktplrefresh($tplfile, $tplfile, @filemtime(FAMOUS_ROOT . $cachefile), $templateid, $cachefile, $tpldir, $file);

    return FAMOUS_ROOT . $cachefile;
}

/**
 * 显示提示信息
 */
function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0)
{
    global $_G;


    $show_message = lang('message', $message, $values);

    include template('common/showmessage');
    dexit();
}

function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = false, $ip = '', $timeout = 15, $block = true, $referer = '')
{
    require_once libfile('function/filesock');
    return _dfsockopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $referer);
}

function dmkdir($dir, $mode = 0777, $makeindex = true)
{
    $dir = dirname($dir);
    if (!is_dir($dir)) {
        dmkdir($dir, $mode, $makeindex);
        @mkdir($dir, $mode);
        @chmod($dir, $mode);
        if (!empty($makeindex)) {
            @touch($dir . '/index.html');
            @chmod($dir . '/index.html', 0777);
        }
    }

    return true;
}

/**
 * 将特殊字符转换为HTML实体字符(支持数组格式)
 *
 * @param string|array $string
 * @return string|array
 */
function dhtmlspecialchars($string)
{
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dhtmlspecialchars($val);
        }
    } else {
        $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', str_replace(array(
            '&',
            '"',
            '<',
            '>'), array(
            '&amp;',
            '&quot;',
            '&lt;',
            '&gt;'), $string));
    }

    return $string;
}

/**
 * 输出一个信息并停止执行当前脚本
 *
 * @param string $message
 * @return void
 */
function dexit($message = '')
{
    echo is_array($message) ? json_encode($message) : $message;
    // output();
    exit();
}

/**
 * 发送原始HTTP标头
 *
 *
 * @param string $string
 * @param boolean $replace  指明是替换掉前一条类似的标头还是增加一条相同类型的标头
 * @param integer $http_response_code   强制将 HTTP 响应代码设为指定值
 * @return void
 */
function dheader($string, $replace = true, $http_response_code = 0)
{
    $string = str_replace(array("\r", "\n"), array('', ''), $string);
    if (empty($http_response_code) || PHP_VERSION < '4.3') {
        @header($string, $replace);
    } else {
        @header($string, $replace, $http_response_code);
    }

    // 如果是Location则停止执行当前脚本
    if (preg_match('/^\s*location:/is', $string)) {
        exit();
    }
}

/**
 * 载入语言
 */
function lang($file, $langvar = null, $vars = array(), $default = null)
{
    global $_G;

    $file .= '/';

    list($path, $file) = explode('/', $file);
    if (!$file) {
        $file = $path;
        $path = '';
    }

    if ($path != 'plugin') {
        $key = $path == '' ? $file : $path . '_' . $file;
        if (!isset($_G['lang'][$key])) {
            include FAMOUS_ROOT . './source/language/' . ($path == '' ? '' : $path . '/') . 'lang_' . $file . '.php';
            $_G['lang'][$key] = $lang;
        }
        $returnvalue = &$_G['lang'];
    } else {
        if (!isset($_G['lang']['plugin'])) {
            include FAMOUS_ROOT . './data/plugindata/lang_plugin.php';
            $_G['lang']['plugin'] = $lang;
        }
        $returnvalue = &$_G['lang']['plugin'];
        $key = &$file;
    }
    $return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
    $return = $return === null ? ($default !== null ? $default : $langvar) : $return;
    if ($vars && is_array($vars)) {
        $searchs = $replaces = array();
        foreach ($vars as $k => $v) {
            $searchs[] = '{' . $k . '}';
            $replaces[] = $v;
        }
        $return = str_replace($searchs, $replaces, $return);
    }

    return $return;
}

/**
 * 检查模板文件是否需要刷新
 */
function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file)
{
    static $tplrefresh, $timestamp;
    if ($tplrefresh === null) {
        $tplrefresh = getglobal('config/output/tplrefresh');
        $timestamp = getglobal('timestamp');
    }

    if (empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($timestamp % $tplrefresh))) {
        if (empty($timecompare) || @filemtime(FAMOUS_ROOT . $subtpl) > $timecompare) {
            require_once FAMOUS_ROOT . '/source/class/class_template.php';
            $template = new template();
            $template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
            return true;
        }
    }
    return false;
}

/**
 * 使用反斜线引用字符串
 *
 * @param array|string $string
 * @param integer $force
 * @return array|string
 */
function daddslashes($string, $force = 1)
{
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            unset($string[$key]);
            $string[addslashes($key)] = daddslashes($val, $force);
        }
    } else {
        $string = addslashes($string);
    }

    return $string;
}

/**
 * 去掉反斜线引用字符串
 *
 * @param  array|string $string
 * @return array|string
 */
function dstripslashes($string)
{
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }

    return $string;
}

/**
 * 加密和解密函数
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    $ckey_length = 4;
    $key = md5($key != '' ? $key : getglobal('authkey'));
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }

}

/**
 * 设置cookie
 */
function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false)
{

    global $_G;

    $config = $_G['config']['cookie'];

    $_G['cookie'][$var] = $value;
    $var = ($prefix ? $config['cookiepre'] : '') . $var;
    $_COOKIE[$var] = $var;

    if ($value == '' || $life < 0) {
        $value = '';
        $life = -1;
    }

    $life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
    $path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'] . '; HttpOnly' : $config['cookiepath'];

    $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
    header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
    if (PHP_VERSION < '5.2.0') {
        setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
    } else {
        setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
    }
}

/**
 * 取出会话ID
 *
 * 没有会话ID则自动创建一个
 */
function getSid()
{
    global $_G;

    $key = 'sid';
    $sid = getcookie($key);
    if (empty($sid) || !preg_match('/[a-zA-Z0-9]/', $sid)) {
        $sid = random(16);
        dsetcookie($key, $sid, 86400);
    }

    return $sid;
}

/**
 * 取出cookie
 *
 * @param mixed $key
 * @return string
 */
function getcookie($key)
{
    global $_G;

    return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
}

/**
 * 纠正序列化字符串中字符串长度的问题
 */
function unserialized($string)
{
    return @unserialize(preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $string));
}

/**
 * 生成随机字符串
 */
function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

/**
 * 判断字符串$string中是否存在$find
 *
 * @param string $string
 * @param string $find
 * @return boolean
 */
function strexists($string, $find)
{
    return !(strpos($string, $find) === false);
}

/**
 * 返回字符型计量单位的字节数
 *
 * <p>返回 128M 字节数 134217728</p>
 * <code>
 * return_bytes('128M');
 * </code>
 *
 * @param string $val
 * @return integer
 */
function return_bytes($val)
{
    $val = trim($val);
    $last = strtolower($val{strlen($val) - 1});
    switch ($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

/**
 * 表单提交检查
 */
function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0)
{
    if (!getgpc($var)) {
        return false;
    } else {
        global $_G;

        if ($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_G['gp_formhash']) && $_G['gp_formhash'] == formhash() && empty($_SERVER['HTTP_X_FLASH_VERSION']) && (empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
            /*
            if(checkperm('seccode')) {
            if($secqaacheck && !check_secqaa($_G['gp_secanswer'], $_G['gp_sechash'])) {
            showmessage('submit_secqaa_invalid');
            }
            if($seccodecheck && !check_seccode($_G['gp_seccodeverify'], $_G['gp_sechash'])) {
            showmessage('submit_seccode_invalid');
            }
            }
            */
            return true;
        } else {
            showmessage('submit_invalid');
        }
    }
}

/**
 * 表单哈希值
 */
function formhash($specialadd = '')
{
    global $_G;

    $hashadd = defined('IN_ADMINCP') ? 'Only For Discuz! Admin Control Panel' : '';
    return substr(md5(substr($_G['timestamp'], 0, -7) . $_G['username'] . $_G['uid'] . $_G['authkey'] . $hashadd . $specialadd), 8, 8);
}

/**
 * 取出页面来源
 */
function dreferer($default = '')
{
    global $_G;

    $default = empty($default) ? (isset($GLOBALS['_t_curapp']) ? $GLOBALS['_t_curapp'] : '') : $default;
    if (empty($_G['referer'])) {
        $referer = !empty($_G['referer']) ? $_G['referer'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
        $parse = parse_url($referer);
        if (!isset($parse['host']) || $parse['host'] == $_SERVER['HTTP_HOST']) {
            $_G['referer'] = preg_replace("/([\?&])((inajax\=[0-9]{1})(&|$))/i", '\\1', $referer);
            $_G['referer'] = preg_replace("/([\?&])((random\=[0-9]{0,6})(&|$))/i", '\\1', $_G['referer']);
            $_G['referer'] = substr($_G['referer'], -1) == '?' ? substr($_G['referer'], 0, -1) : $_G['referer'];
        }
    } else {
        // $_G['referer'] = htmlspecialchars($_G['referer']);
    }

    if (strpos($_G['referer'], 'member.php?mod=login')) {
        $_G['referer'] = $default;
    }

    return strip_tags($_G['referer']);
}

function diconv($str, $in_charset, $out_charset = CHARSET, $ForceTable = false)
{
    global $_G;

    $in_charset = strtoupper($in_charset);
    $out_charset = strtoupper($out_charset);

    if (empty($str) || $in_charset == $out_charset) {
        return $str;
    }

    $out = '';

    if (!$ForceTable) {
        if (function_exists('iconv')) {
            $out = iconv($in_charset, $out_charset . '//IGNORE', $str);
        } elseif (function_exists('mb_convert_encoding')) {
            $out = mb_convert_encoding($str, $out_charset, $in_charset);
        }
    }

    if ($out == '') {
        require_once libfile('class/chinese');
        $chinese = new Chinese($in_charset, $out_charset, true);
        $out = $chinese->Convert($str);
    }

    return $out;
}

function cutstr($string, $length, $dot = '...', $charset = 'utf-8')
{
    if (strlen($string) <= $length) {
        return $string;
    }

    $pre = chr(1);
    $end = chr(1);
    $string = str_replace(array(
        '&amp;',
        '&quot;',
        '&lt;',
        '&gt;'), array(
        $pre . '&' . $end,
        $pre . '"' . $end,
        $pre . '<' . $end,
        $pre . '>' . $end), $string);

    $strcut = '';
    if ($charset == 'utf-8') {

        $n = $tn = $noc = 0;
        while ($n < strlen($string)) {

            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }

            if ($noc >= $length) {
                break;
            }

        }
        if ($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);

    } else {
        for ($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
        }
    }

    $strcut = str_replace(array(
        $pre . '&' . $end,
        $pre . '"' . $end,
        $pre . '<' . $end,
        $pre . '>' . $end), array(
        '&amp;',
        '&quot;',
        '&lt;',
        '&gt;'), $strcut);

    $pos = strrpos($strcut, chr(1));
    if ($pos !== false) {
        $strcut = substr($strcut, 0, $pos);
    }

    return $strcut . $dot;
}

/**
 * 返回当前UNIX时间戳 精确到微秒
 *
 * @param void
 * @return float
 */
function dmicrotime()
{
    return array_sum(explode(' ', microtime()));
}

/**
 * 设置全局变量
 *
 * @param string $key
 * @param mixed  $value
 * @param string $group
 * @return boolean
 */
function setglobal($key, $value, $group = null)
{
    global $_G;

    $k = explode('/', $group === null ? $key : $group . '/' . $key);
    switch (count($k)) {
        case 1:
            $_G[$k[0]] = $value;
            break;
        case 2:
            $_G[$k[0]][$k[1]] = $value;
            break;
        case 3:
            $_G[$k[0]][$k[1]][$k[2]] = $value;
            break;
        case 4:
            $_G[$k[0]][$k[1]][$k[2]][$k[3]] = $value;
            break;
        case 5:
            $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] = $value;
            break;
        case 6:
            $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]][$k[5]] = $value;
            break;
    }

    return true;
}

/**
 * 取出全局变量
 *
 * @param string $key
 * @param string $group
 * @return void
 */
function getglobal($key, $group = null)
{
    global $_G;

    $k = explode('/', $group === null ? $key : $group . '/' . $key);
    switch (count($k)) {
        case 1:
            return isset($_G[$k[0]]) ? $_G[$k[0]] : null;
            break;
        case 2:
            return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null;
            break;
        case 3:
            return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null;
            break;
        case 4:
            return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null;
            break;
        case 5:
            return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null;
            break;
        case 6:
            return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]][$k[5]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]][$k[5]] : null;
            break;
    }

    return null;
}

function getgpc($k, $type = 'GP')
{
    $type = strtoupper($type);
    switch ($type) {
        case 'G':
            $var = &$_GET;
            break;
        case 'P':
            $var = &$_POST;
            break;
        case 'C':
            $var = &$_COOKIE;
            break;
        default:
            if (isset($_GET[$k])) {
                $var = &$_GET;
            } else {
                $var = &$_POST;
            }
            break;
    }

    return isset($var[$k]) ? $var[$k] : null;
}


/**
 * 返回附件的完整物理路径
 */
function getattachmentpath($attachment, $type = 'weibo')
{
    return FAMOUS_ROOT . getglobal('config/setting/attachdir') . $type . '/' . $attach['attachment'];
}

/**
 * 载入指定的网页
 *
 * @param string $url
 * @return void
 */
function loadPage($loadUrl)
{
    global $_G;

    // $parse = parse_url($loadUrl);

    // 使用启动模板
    include template('diy:common/start');
    exit;
}

/**
 * 取出CSS路径
 */
function getCss($filename, $dirname = 'common', $path = false)
{
    $mini = STATICURL . "{$dirname}/css/{$filename}.css?ver=" . WEIBO_RELEASE;

    if ($path) {
        return $mini;
    }

    return '<link href="' . $mini . '" rel="stylesheet" type="text/css" />';
}

/**
 * 取出JS路径
 *
 * @param string $filename
 * @param string $dirname
 * @return string
 */
function getScript($filename, $dirname = 'common', $path = false)
{
    // 调试状态下检测JS是否被修改
    if (ENVIRONMENT != 'production') {
        $sourcePath = FAMOUS_ROOT . "static/{$dirname}/js/{$filename}.js";
        $targetPath = FAMOUS_ROOT . "static/{$dirname}/js/{$filename}.min.js";
        // 清除文件状态缓存
        clearstatcache();
        // JS源文件被修改后重新压缩JS文件
        if (@filemtime($sourcePath) > @filemtime($targetPath)) {
            require_once libfile('class/packer');
            $packer = new JavaScriptPacker(file_get_contents($sourcePath), 0, false, false);
            // 写入压缩后的文件
            @chmod($targetPath, 0666);
            file_put_contents($targetPath, $packer->pack());
        }
    }

    $mini = STATICURL . "{$dirname}/js/{$filename}.min.js?ver=" . WEIBO_RELEASE; // 压缩后的JS文件

    if ($path) {
        return $mini;
    }

    return '<script src="' . $mini . '" type="text/javascript"></script>';
}

/**
 * 构造URL
 */
function url($params = array())
{
    global $_G;

    $url = SITEURL;

    if (isset($params['app']) && in_array($params['app'], $_G['config']['weibo']['app'])) {
        $url .= CURSCRIPT . '/index.php';
    } else {
        $url .= CURSCRIPT . '.php';
    }

    if (!isset($params['mod']))
        $params['mod'] = $_G['mod'];
    if (!isset($params['action']))
        $params['action'] = $_G['action'];

    $url .= '?' . http_build_query($params);

    return $url;
}

/**
 * 取出当前页面的URL
 *
 * @return string
 */
function getCurrentURL()
{
    global $_G;

    $url = getglobal('config/setting/siteurl');

    if (APPTYPEID) {
        $url .= CURSCRIPT . '/index.php';
    } else {
        $url .= CURSCRIPT . '.php';
    }

    if (!empty($_SERVER['QUERY_STRING'])) {
        parse_str($_SERVER['QUERY_STRING'], $params);
        unset($params['inajax'], $params['random']);
        $url .= '?' . http_build_query($params);
    }

    return $url;
}

/**
 * 运行钩子
 *
 * @return void
 */
function runhooks()
{
    global $_G;

    if (strstr($_SERVER['HTTP_HOST'], 'test') && !empty($_G['username']) && !@in_array($_G['username'], $_G['config']['weibo']['testuser'])) {
        showmessage('weibo_internal_test');
    } elseif ($_G['config']['weibo']['upgrade'] && !@in_array($_G['clientip'], $_G['config']['weibo']['testip'])) {
        showmessage('weibo_upgrade');
    }
}



function dstrlen($str, $type = 'tencent')
{

    $count = 0;
    for ($i = 0; $i < strlen($str); $i++) {
        $value = ord($str[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223) {
                $i++;
            } elseif ($value >= 224 && $value <= 239) {
                $i = $i + 2;
            } elseif ($value >= 240 && $value <= 247) {
                $i = $i + 3;
            }
        }
        $count++;
    }
    if ($type == 'sina') {
        $min = 20;
        $sina = '/http:\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z_\$\.\+\!\*\(\)\/,:;@&=\?\~\#\%]*)*/';
        preg_match_all($sina, $str, $array);
    } else {
        $min = 22;
        $tencent = '/((news|telnet|nttp|file|http|ftp|https):\/\/){1}(([-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\\.[0-9]{1,3}){3}))(:[0-9]*)?(\/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?\/~\\#\\%]*)*/';
        preg_match_all($tencent, $str, $array);
    }
    $len = 0;
    if (is_array($array) && !empty($array)) {
        foreach ($array[0] as $v) {
            if (strlen($v) > $min || $type == 'tencent') {
                $len += strlen($v) - $min;
            }
        }
    }
    return $count - $len;
}

/**
 * 检查会员黑名单并将会员的IP地址直接加入IP黑名单
 *
 * @param string $username 会员用户名
 * @param string $ip       IP地址
 * @return boolean
 */
function checkBlacklist($username, $ip)
{
    global $_G;

    $ipBlack = ipBlacklist('get');
    if (in_array($ip, $ipBlack)) {
        return true;
    }

    $memberBlack = memberBlacklist('get');
    if (!in_array($username, $memberBlack)) {
        return false;
    }

    $ipBlack[] = $ip;
    ipBlacklist('set', $ipBlack);

    return true;
}

/**
 * 会员黑名单操作类
 *
 * @param string $cmd  操作(get|set|rm)
 * @param array  $data 黑名单数组
 * @param integer $ttl  有效时间(秒)
 * @return mixed
 */
function memberBlacklist($cmd, $data = null, $ttl = 0)
{
    global $_G;

    $black = array();
    $index = 'member_black_list';
    $file = FAMOUS_ROOT . 'data/MemberBlack.txt';

    if ($cmd == 'get') {

        $black = memory('get', $index);
        if (empty($black)) {
            $black = @file($file);
            $black = @array_map('trim', $black);
        }
        $black = empty($black) ? array() : $black;

    } elseif ($cmd == 'set') {

        $ttl = empty($ttl) ? 15 * 86400 : $ttl;
        memory('set', $index, $data, $ttl);
        file_put_contents($file, implode("\n", $data));

    } elseif ($cmd == 'rm') {

        memory('rm', $index);
        file_put_contents($file, '');
    }

    return $black;
}

/**
 * IP黑名单操作类
 *
 * @param string  $cmd  操作(get|set|rm)
 * @param array   $data 黑名单数组
 * @param integer $ttl  有效时间(秒)
 * @return mixed
 */
function ipBlacklist($cmd, $data = null, $ttl = 0)
{
    global $_G;

    $black = array();
    $index = 'ip_black_list';
    $file = FAMOUS_ROOT . 'data/IpBlack.txt';

    if ($cmd == 'get') {

        $black = memory('get', $index);
        if (empty($black)) {
            $black = @file($file);
            $black = @array_map('trim', $black);
        }
        $black = empty($black) ? array() : $black;

    } elseif ($cmd == 'set') {

        $ttl = empty($ttl) ? 15 * 86400 : $ttl;
        memory('set', $index, $data, $ttl);
        file_put_contents($file, implode("\n", $data));

    } elseif ($cmd == 'rm') {

        memory('rm', $index);
        file_put_contents($file, '');
    }

    return $black;
}


function sendmail($toemail, $subject, $message, $from = '')
{
    global $_G;

    if (empty($_G['config']['setting']['mail']) || !is_array($_G['config']['setting']['mail'])) {
        return false;
    }
    $message = preg_replace("/href\=\"(?!http\:\/\/)(.+?)\"/i", 'href="' . $_G['config']['siteurl'] . '\\1"', $message);

    $message = <<< EOT
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=$_G[charset]">
<title>$subject</title>
</head>
<body>
$message
</body>
</html>
EOT;

    $maildelimiter = $_G['config']['setting']['mail']['maildelimiter'] == 1 ? "\r\n" : ($_G['config']['setting']['mail']['maildelimiter'] == 2 ? "\r" : "\n");
    $mailusername = isset($_G['config']['setting']['mail']['mailusername']) ? $_G['config']['setting']['mail']['mailusername'] : 1;

    if ($_G['config']['setting']['mail']['mailsend'] == 3) {
        $email_from = empty($from) ? $_G['config']['setting']['adminemail'] : $from;
    } else {
        $email_from = $from == '' ? '=?' . CHARSET . '?B?' . base64_encode($_G['config']['setting']['sitename']) . "?= <" . $_G['config']['setting']['adminemail'] . ">" : (preg_match('/^(.+?) \<(.+?)\>$/', $from, $mats) ? '=?' . CHARSET . '?B?' . base64_encode($mats[1]) . "?= <$mats[2]>" : $from);
    }

    $email_to = preg_match('/^(.+?) \<(.+?)\>$/', $toemail, $mats) ? ($mailusername ? '=?' . CHARSET . '?B?' . base64_encode($mats[1]) . "?= <$mats[2]>" : $mats[2]) : $toemail;

    $email_subject = '=?' . CHARSET . '?B?' . base64_encode(preg_replace("/[\r|\n]/", '', '[' . $_G['config']['setting']['sitename'] . '] ' . $subject)) . '?=';
    $email_message = chunk_split(base64_encode(str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $message))))));
    $host = $_SERVER['HTTP_HOST'];
    $version = '2.0';
    $headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: $host $version {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=" . CHARSET . "{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";
    if ($_G['config']['setting']['mail']['mailsend'] == 1) {
        if (function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
            return true;
        }
        return false;

    } elseif ($_G['config']['setting']['mail']['mailsend'] == 2) {
        if (!$fp = fsocketopen($_G['config']['setting']['mail']['server'], $_G['config']['setting']['mail']['port'], $errno, $errstr, 30)) {
            return false;
        }

        stream_set_blocking($fp, true);

        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != '220') {
            return false;
        }

        fputs($fp, ($_G['config']['setting']['mail']['auth'] ? 'EHLO' : 'HELO') . " uchome\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
            return false;
        }

        while (1) {
            if (substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
                break;
            }
            $lastmessage = fgets($fp, 512);
        }

        if ($_G['config']['setting']['mail']['auth']) {
            fputs($fp, "AUTH LOGIN\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 334) {
                return false;
            }

            fputs($fp, base64_encode($_G['config']['setting']['mail']['auth_username']) . "\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 334) {
                return false;
            }

            fputs($fp, base64_encode($_G['config']['setting']['mail']['auth_password']) . "\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 235) {
                return false;
            }

            $email_from = $_G['config']['setting']['mail']['from'];
        }

        fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 250) {
            fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 250) {
                return false;
            }
        }

        fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail) . ">\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 250) {
            fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail) . ">\r\n");
            $lastmessage = fgets($fp, 512);
            return false;
        }

        fputs($fp, "DATA\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 354) {
            return false;
        }

        $timeoffset = $_G['config']['setting']['timeoffset'];
        if (function_exists('date_default_timezone_set')) {
            @date_default_timezone_set('Etc/GMT' . ($timeoffset > 0 ? '-' : '+') . (abs($timeoffset)));
        }

        $headers .= 'Message-ID: <' . date('YmdHs') . '.' . substr(md5($email_message . microtime()), 0, 6) . rand(100000, 999999) . '@' . $_SERVER['HTTP_HOST'] . ">{$maildelimiter}";
        fputs($fp, "Date: " . date('r') . "\r\n");
        fputs($fp, "To: " . $email_to . "\r\n");
        fputs($fp, "Subject: " . $email_subject . "\r\n");
        fputs($fp, $headers . "\r\n");
        fputs($fp, "\r\n\r\n");
        fputs($fp, "$email_message\r\n.\r\n");
        $lastmessage = fgets($fp, 512);
        fputs($fp, "QUIT\r\n");

        return true;

    } elseif ($_G['config']['setting']['mail']['mailsend'] == 3) {

        ini_set('SMTP', $_G['config']['setting']['mail']['server']);
        ini_set('smtp_port', $_G['config']['setting']['mail']['port']);
        ini_set('sendmail_from', $email_from);

        if (function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
            return true;
        }
        return false;
    }
}


function fsocketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15)
{
    $fp = '';
    if (function_exists('fsockopen')) {
        $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
    } elseif (function_exists('pfsockopen')) {
        $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
    } elseif (function_exists('stream_socket_client')) {
        $fp = @stream_socket_client($hostname . ':' . $port, $errno, $errstr, $timeout);
    }
    return $fp;
}



function avatar($uid, $size = 'big')
{
    $fullpath = FAMOUS_ROOT . 'data/attachment/avatar/' . get_avatar($uid, $size);
    if (file_exists($fullpath)) {
        return SITEURL . 'data/attachment/avatar/' . get_avatar($uid, $size);
    } else {
        return SITEURL . 'static/spring/images/noavatar_' . $size . '.gif';
    }
}
function check_avatar($uid, $size = 'middle')
{
    $fullpath = FAMOUS_ROOT . 'data/attachment/avatar/' . get_avatar($uid, $size);
    if (file_exists($fullpath)) {
        return true;
    } else {
        return false;
    }
}

function get_avatar($uid, $size = 'big')
{
    $size = in_array($size, array(
        'big',
        'middle',
        'small')) ? $size : 'middle';
    $uid = abs(intval($uid));
    $uid = sprintf("%09d", $uid);
    $dir1 = substr($uid, 0, 3);
    $dir2 = substr($uid, 3, 2);
    $dir3 = substr($uid, 5, 2);
    return $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($uid, -2) . "_avatar_$size.jpg";
}




function writelog($file, $log) {
	global $_G;
	

	$yearmonth = dgmdate(TIMESTAMP, 'Ym', $_G['config']['setting']['timeoffset']);
	$logdir = FAMOUS_ROOT.'./data/log/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strpos($entry, $yearmonth.'_'.$file) !== false) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
		}
		fclose($fp);
	}
}



function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {
	global $_G;
	$format == 'u' && !$_G['setting']['dateconvert'] && $format = 'dt';
	static $dformat, $tformat, $dtformat, $offset, $lang;
	if($dformat === null) {
		$dformat = getglobal('setting/dateformat');
		$tformat = getglobal('setting/timeformat');
		$dtformat = $dformat.' '.$tformat;
		$offset = getglobal('member/timeoffset');
		$lang = lang('core', 'date');
	}
	$timeoffset = $timeoffset == 9999 ? $offset : $timeoffset;
	$timestamp += $timeoffset * 3600;
	$format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
	if($format == 'u') {
		$todaytimestamp = TIMESTAMP - (TIMESTAMP + $timeoffset * 3600) % 86400 + $timeoffset * 3600;
		$s = gmdate(!$uformat ? str_replace(":i", ":i:s", $dtformat) : $uformat, $timestamp);
		$time = TIMESTAMP + $timeoffset * 3600 - $timestamp;
		if($timestamp >= $todaytimestamp) {
			if($time > 3600) {
				return '<span title="'.$s.'">'.intval($time / 3600).'&nbsp;'.$lang['hour'].$lang['before'].'</span>';
			} elseif($time > 1800) {
				return '<span title="'.$s.'">'.$lang['half'].$lang['hour'].$lang['before'].'</span>';
			} elseif($time > 60) {
				return '<span title="'.$s.'">'.intval($time / 60).'&nbsp;'.$lang['min'].$lang['before'].'</span>';
			} elseif($time > 0) {
				return '<span title="'.$s.'">'.$time.'&nbsp;'.$lang['sec'].$lang['before'].'</span>';
			} elseif($time == 0) {
				return '<span title="'.$s.'">'.$lang['now'].'</span>';
			} else {
				return $s;
			}
		} elseif(($days = intval(($todaytimestamp - $timestamp) / 86400)) >= 0 && $days < 7) {
			if($days == 0) {
				return '<span title="'.$s.'">'.$lang['yday'].'&nbsp;'.gmdate($tformat, $timestamp).'</span>';
			} elseif($days == 1) {
				return '<span title="'.$s.'">'.$lang['byday'].'&nbsp;'.gmdate($tformat, $timestamp).'</span>';
			} else {
				return '<span title="'.$s.'">'.($days + 1).'&nbsp;'.$lang['day'].$lang['before'].'</span>';
			}
		} else {
			return $s;
		}
	} else {
		return gmdate($format, $timestamp);
	}
}

function dmktime($date) {
	if(strpos($date, '-')) {
		$time = explode('-', $date);
		return mktime(0, 0, 0, $time[1], $time[2], $time[0]);
	}
	return 0;
}


